package Sort.sort2021;

/**
 * @author leiwenkang <leiwenkang@kuaishou.com>
 * Created on 2021-03-12
 */
public class Sort插入排序 {
    public static void main(String[] args) {
        int[] array = {3, 5, 7, 2, 1, 4, 8, 9, 6};
        sort(array);
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + " ");
        }
    }

    public static void sort(int[] array) {
        if (array == null || array.length == 0) {
            return;
        }

        for (int i = 1; i < array.length; i++) {
            if (array[i] < array[i - 1]) {
                int value = array[i];
                int j;
                for (j = i - 1; j >= 0 && array[j] > value; j--) {
                    array[j + 1] = array[j];
                }
                array[j + 1] = value;
            }
        }
    }
}
